package com.xatz.scanner

import android.graphics.Bitmap
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.zxing.BarcodeFormat
import com.google.zxing.MultiFormatWriter
import com.google.zxing.common.BitMatrix
import com.xatz.scanner.databinding.ActivityLookBarCodeBinding
import timber.log.Timber

/**
 * Created by tdq on 2022/1/14.
 *
 * 查看条码
 */
class LookBarCodeActivity: AppCompatActivity() {

    private val code by lazy { intent.getStringExtra("code") }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val mBinding = ActivityLookBarCodeBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        val bitmap = createOneDCode(code)
        Timber.e(bitmap?.height.toString())
        Timber.e(bitmap?.width.toString())
        mBinding.ivCode.setImageBitmap(bitmap)
    }

    private fun createOneDCode(content: String?): Bitmap? {
        // 生成一维条码,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
        val matrix: BitMatrix = MultiFormatWriter().encode(
            content,
            BarcodeFormat.CODE_128, 500, 200
        )
        val width: Int = matrix.width
        val height: Int = matrix.height
        val pixels = IntArray(width * height)
        for (y in 0 until height) {
            for (x in 0 until width) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = -0x1000000
                }
            }
        }
        val bitmap = Bitmap.createBitmap(
            width, height,
            Bitmap.Config.ARGB_8888
        )
        // 通过像素数组生成bitmap,具体参考api
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height)
        return bitmap
    }
}